package com.example.common.util.lock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Collections;

@Component
public class RedisLockUtils {

    @Autowired
    private RedisTemplate redisTemplate;

    private static final Long LOCK_REDIS_TIMEOUT = 10L;
    public static final Long LOCK_REDIS_WAIT = 500L;

    public <T> Boolean getLock(String key, T value){
        Boolean lockStatus = this.redisTemplate.opsForValue().setIfAbsent(key, value, Duration.ofSeconds(LOCK_REDIS_TIMEOUT));
        return lockStatus;
    }

    public <T> Long releaseLock(String key, T value){
        String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript, Long.class);
        Long releaseStatus = (Long) this.redisTemplate.execute(redisScript, Collections.singletonList(key), value);
        return releaseStatus;
    }
}